﻿using ClosedXML.Excel;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SmartProduction.Domain;
using SmartProduction.Domain.采购委外订单;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue;
using SmartProduction.Write.API.Application.Commands.DepartCommand;
using SmartProduction.Write.API.Application.Commands.EnterpriseCommand;
using SmartProduction.Write.API.Application.Commands.ProcessRouteCommand;
using SmartProduction.Write.API.Application.Commands.PurchaseCommand;
using SmartProduction.Write.API.Application.Commands.SalesOrderDetailsCommand;
using SmartProduction.Write.API.Application.Commands.SupplierCommand;
using SmartProduction.Write.API.Application.Commands.work_InvoiceCommand;

namespace SmartProduction.Write.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class PurchaseController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly DataDbContext db;

        public PurchaseController(IMediator mediator, DataDbContext db)
        {
            this.mediator = mediator;
            this.db = db;
        }


        /// <summary>
        /// 部门添加
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<object>> DepartCreate(DepartCreateCommand request)
        {
            try
            {
                return await  mediator.Send(request);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 供应商添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<object>> SupperCreate(SupplierCreateCommand request)
        {
            try
            {

                return await mediator.Send(request);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 供应商修改
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<object>> SupperUpdate(SupplierUpdateCommand request)
        {
            try
            {

                return await mediator.Send(request);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 供应商删除
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<object>> SupperDelete(SupplierDeleteCommand request)
        {
            try
            {

                return await mediator.Send(request);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 工艺路线添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<object>> ProcessCreate(ProcessRouteCreateCommand request)
        {
            try
            {

                return await mediator.Send(request);
            }
            catch (Exception)
            {

                throw;
            }
        }


        /// <summary>
        /// 企业管理添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<object>> EnterPriseCreate(EnterpriseCreateCommand request, CancellationToken cancellationToken)
        {
            try
            {

                return await mediator.Send(request);
            }
            catch (Exception)
            {

                throw;
            }
        }


        /// <summary>
        /// 采购委外添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost]

        public async Task<APIResult<object>> PurchaseCreate(PurchaseCreateCommand request)
        {
            try
            {

                return await mediator.Send(request);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 采购委外修改
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<object>> PurchaseUpdate(PurchaseUpdateCommand request)
        {
            try
            {

                return await mediator.Send(request);
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 采购委外详情添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<object>> PurchasedetailsCreate(PurchasedetailsCreateCommand request)
        {
            try
            {

                return await mediator.Send(request);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 采购委外详情双表添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<object>> PurchaseCreatedetailsCreate(PurchaseCreatedetailsCreateCommand request)
        {
            try
            {

                return await mediator.Send(request);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 采购委外详情双表修改
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<object>> PurchaseUpdatedetailsUpdate(PurchaseUpdatedetailsUpdateCommand request)
        {
            try
            {

                return await mediator.Send(request);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 审批状态修改
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<object>> Handle(PurchaseStatusUpdateCommand request)
        {
            try
            {

                return await mediator.Send(request);
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 导入工作中心管理
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> ImportInventories(IFormFile file)
        {
            APIResult<string> result = new APIResult<string>();
            try
            {
                // 检查上传文件是否为空
                if (file == null || file.Length <= 0)
                {
                    result.Code = APIEnums.查询失败;
                    result.Msg = "未上传文件或文件为空";
                    return BadRequest(result);
                }

                // 检查文件扩展名是否为 Excel 格式
                var fileExtension = Path.GetExtension(file.FileName);
                if (fileExtension != ".xlsx" && fileExtension != ".xls")
                {
                    result.Code = APIEnums.查询失败;
                    result.Msg = "仅支持上传 Excel 文件";
                    return BadRequest(result);
                }

                // 使用 MemoryStream 读取文件内容
                using (var stream = new MemoryStream())
                {
                    await file.CopyToAsync(stream);
                    using (var workbook = new XLWorkbook(stream))
                    {
                        var worksheet = workbook.Worksheet(1); // 获取第一个工作表
                        var rows = worksheet.RowsUsed().Skip(1); // 跳过第一行（表头）

                        List<Supplier> job = new List<Supplier>();

                        foreach (var row in rows)
                        {
                            var sup = new Supplier();
                            sup.SupplierCode = row.Cell(1).GetValue<string>();
                            sup.SupplierName = row.Cell(2).GetValue<string>();
                            sup.SupplierType = row.Cell(3).GetValue<string>();
                            sup.SupplierAddress = row.Cell(4).GetValue<string>();
                            sup.SupplierPhone = row.Cell(5).GetValue<string>();
                            sup.City = row.Cell(6).GetValue<string>();
                            sup.Status = row.Cell(7).GetValue<string>();
                            sup.ApprovalStatus = row.Cell(8).GetValue<int>();
                            sup.Country = row.Cell(9).GetValue<string>();
                            sup.SupplierCategory = row.Cell(10).GetValue<string>();
                            sup.SupplierTag = row.Cell(11).GetValue<string>();
                            sup.CompanyFlag = row.Cell(12).GetValue<string>();
                            sup.OutsourcingFlag = row.Cell(13).GetValue<string>();

                            // 添加到要插入的列表中
                            job.Add(sup);
                        }
                        await db.AddRangeAsync(job);
                        await db.SaveChangesAsync();
                        result.Code = APIEnums.添加成功;
                        result.Msg = "导入成功";
                        result.data = job.Count.ToString();
                    }
                }
            }
            catch (Exception ex)
            {

                result.Code = APIEnums.添加失败;
                result.Msg = "导入失败，原因：" + ex.Message;
                return StatusCode(500, result);
            }
            return Ok(result);
        }

        /// <summary>
        /// 销售订单明细新增
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回</returns>
        [HttpPost]
        public Task<APIResult<object>> SalesOrderDetailAdd(SalesOrderDetailsCreateCommand command)
        {
            try
            {
                return mediator.Send(command);
            }
            catch (Exception)
            {

                throw;
            }
        }

       
    }
    
}
